package com.elitel.frame.base.controller;

import com.elitel.frame.base.component.exportprojectdata.ExportProjectData;
import com.elitel.frame.base.component.exportprojectdata.ProgressSingleton;
import com.elitel.frame.base.service.SysProjectService;
import com.elitel.frame.main.entity.ext.SysProjectExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description 系统首页控制器
 * @author guoyanfei
 * @date 2017/12/08
 */
@Controller
@RequestMapping("/system/index")
public class SystemIndexController {
  private static final Logger logger = LoggerFactory.getLogger(SystemIndexController.class);
  @Autowired private ProgressSingleton progressSingleton;
  @Autowired private ExportProjectData exportProjectData;
  @Autowired private SysProjectService sysProjectService;

  /**
   * @description 查询所有项目信息
   * @param request
   * @return SysProjec集合
   * @author guoyanfei
   * @date 2017/12/08
   */
  @RequestMapping("/getAllProject")
  @ResponseBody
  public List<SysProjectExt> getAllProject(HttpServletRequest request) {
    List<SysProjectExt> sysProjects = new ArrayList<SysProjectExt>();
    try {
      sysProjects = sysProjectService.getProjectExtList();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return sysProjects;
  }

  /**
   * show 导出项目数据
   *
   * @param pcode(项目code)
   * @author guoyanfei
   * @date 2017/12/11
   */
  @RequestMapping("/exportProjectData")
  @ResponseBody
  public String exportProjectData(HttpServletRequest request) {
    // 清空进度条信息
    progressSingleton.remove("ratio");
    progressSingleton.remove("message");

    String filename = "";
    try {
      String path = "main-frame-file/improtDatatemp";
      File uploadRootDir = new File(path);
      if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();
      }
      String pcode = request.getParameter("pcode");
      filename = exportProjectData.exportProjectDataBypcode(pcode, progressSingleton, path);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return filename;
  }

  /**
   * show 查询导出数据实时进度
   *
   * @author guoyanfei
   * @date 2017/12/12
   */
  @RequestMapping("/getProgressInfo")
  @ResponseBody
  public Map<String, String> getProgressInfo(HttpServletRequest request) {
    Map<String, String> maps = new HashMap<String, String>();
    try {
      String ratio = progressSingleton.get("ratio").toString();
      String message = progressSingleton.get("message").toString();
      if (ratio == null || ratio.equals("")) {
        ratio = "0";
      }
      if (message == null || message.equals("")) {
        message = "正在导出...";
      }
      maps.put("ratio", ratio);
      maps.put("message", message);
    } catch (Exception e) {
      // logger.error(e.getMessage(),e);
    }
    return maps;
  }

  /**
   * @description 下载导出的数据文件
   * @param filename(文件名称)
   * @author guoyanfei
   * @date 2017/12/13
   */
  @RequestMapping("/downloadData")
  @ResponseBody
  public void downloadData(HttpServletRequest request, HttpServletResponse response) {
    try {
      String filename = request.getParameter("filename");
      String path = "main-frame-file/improtDatatemp";
      File uploadRootDir = new File(path);
      if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();
      }
      // 设置响应头，控制浏览器下载该文件
      response.setHeader("content-disposition", "attachment;filename=" + filename);
      // 读取下载的文件，保存到文件输入流
      FileInputStream fileInputStream = new FileInputStream(path + "/" + filename);
      // 创建输出流
      OutputStream out = response.getOutputStream();
      // 创建缓存区
      byte buffer[] = new byte[1024];
      int length = 0;
      while ((length = fileInputStream.read(buffer)) > 0) {
        out.write(buffer, 0, length);
      }
      fileInputStream.close();
      out.close();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  @RequestMapping("/importData")
  @ResponseBody
  public String importProjectData(
      @RequestParam("file") MultipartFile file, HttpServletRequest request) {
    String message = "";

    try {
      InputStream inputStream = file.getInputStream();
      message = exportProjectData.importData(inputStream, progressSingleton);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return message;
  }
}
